package _166_Fraction_to_Recurring_Decimal;

import java.util.LinkedList;

/**
 * Created by 孙加辉 on 2018/7/22.
 */
class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        String res = "";
        //判断正负符号
        boolean flag = Long.parseLong(""+numerator)*Long.parseLong(""+denominator)>=0;
        Long numerator2 = Long.parseLong(""+numerator)>0?Long.parseLong(""+numerator):-Long.parseLong(""+numerator);
        Long denominator2 = Long.parseLong(""+denominator)>0?Long.parseLong(""+denominator):-Long.parseLong(""+denominator);
        //整数部分除法
        while(numerator2>=denominator2){
            res += ""+numerator2/denominator2;
            numerator2 -= (numerator2/denominator2)*denominator2;
        }
        //判断是否整除
        res = res.equals("")?"0":res;
        if(numerator2 != 0)
            res += ".";
        else{
            if(flag)
                return res;
            else
                return "-"+res;
        }
        LinkedList<Long> numbers = new LinkedList<Long>();
        LinkedList<Long> rem = new LinkedList<Long>();
        int start = -1;
        //小数部分除法
        while(numerator2>0){
            //System.out.println("numbers:"+numbers);
            numbers.add(Long.parseLong(""+numerator2));
            numerator2 *= 10;
            Long temp = Long.parseLong(""+numerator2)/Long.parseLong(""+denominator2);
            rem.add(temp);
            numerator2 -= temp*denominator2;
            if(numbers.contains(Long.parseLong(""+numerator2))){
                start = numbers.indexOf(Long.parseLong(""+numerator2));
                //System.out.println("start:"+start);
                break;
            }

        }
        //无循环时的输出
        if(start != -1){
            for(int i=0;i<start;i++){
                res+=rem.get(i);
            }
            res+="(";
            for(int i=start;i<rem.size();i++){
                res+=rem.get(i);
            }
            res+=")";
        }//有循环时的输出
        else{
            for(int i=0;i<rem.size();i++){
                res+=rem.get(i);
            }
        }
        if(!flag){
            res = "-"+res;
        }
        //System.out.println(numbers);
        //System.out.println(rem);
        return res;
    }
}
public class _166_Fraction_to_Recurring_Decimal {
    public static void main(){
        Solution solution = new Solution();
        System.out.println(solution.fractionToDecimal(1,23));
    }
}
